package com.rds.material.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rds.common.annotation.Log;
import com.rds.common.api.material.domain.MaterialBill;
import com.rds.common.api.material.domain.RdaPart;
import com.rds.common.api.material.domain.RdaPartDynamicattributevalue;
import com.rds.common.core.controller.BaseController;
import com.rds.common.core.domain.AjaxResult;
import com.rds.common.core.page.TableDataInfo;
import com.rds.common.enums.BusinessType;
import com.rds.common.utils.SecurityUtils;
import com.rds.common.utils.poi.ExcelUtil;
import com.rds.common.utils.uuid.SnowFlakeUtils;

import com.rds.material.mapper.MaterialBillMapper;
import com.rds.material.service.IMaterialBillService;
import com.rds.material.service.IRdaPartDynamicattributevalueService;
import com.rds.material.service.IRdaPartService;
import com.rds.material.service.impl.MaterialBillServiceImpl;
import com.rds.system.domain.Sharing;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 材料清单Controller
 *
 * @author rds
 * @date 2021-08-17
 */
@RestController
@RequestMapping("/pms/materialBill")
public class MaterialBillController extends BaseController
{
    @Autowired
    private IRdaPartDynamicattributevalueService rdaPartDynamicattributevalueService;

    @Autowired
    private MaterialBillServiceImpl materialBillService;
    @Autowired
    private MaterialBillMapper materialBillMapper;
    @Autowired
    private IRdaPartService rdaMaterialService;

    @Autowired
    private IMaterialBillService iMaterialBillService;

    /**
     * 查询项目WBS列表
     */
    @PreAuthorize("@ss.hasPermi('pms:ebom:list')")
    @GetMapping("/list")
    public TableDataInfo list(MaterialBill materialBill)
    {
//        startPage();
//        List<MaterialBill> materialBillList = materialBillService.selectTreeList(materialBill);
        List<MaterialBill> materialBillList = iMaterialBillService.selectTreeList(materialBill);
        return getDataTable(materialBillList);
    }

    /**
     * 查询WBS下级列表
     */
    @PreAuthorize("@ss.hasPermi('pms:ebom:list')")
    @GetMapping("/lowerlist")
    public TableDataInfo lowerlist(MaterialBill materialBill)
    {
        startPage();
        List<MaterialBill> list = materialBillService.selectMaterialBillSubordinate(materialBill.getParentid());
        return getDataTable(list);
    }

    /**
     * 导出项目WBS列表
     */
    @PreAuthorize("@ss.hasPermi('pms:ebom:export')")
    @Log(title = "项目WBS", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(MaterialBill rdaPmswbs)
    {
        List<MaterialBill> list = materialBillService.selectMaterialBillList(rdaPmswbs);
        ExcelUtil<MaterialBill> util = new ExcelUtil<MaterialBill>(MaterialBill.class);
        return util.exportExcel(list, "pmswbs");
    }

    /**
     * 获取项目WBS详细信息
     */
    @PreAuthorize("@ss.hasPermi('pms:ebom:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(materialBillService.selectMaterialBillById(id));
    }

    /**
     * 新增项目WBS
     */
    @PreAuthorize("@ss.hasPermi('pms:ebom:add')")
    @Log(title = "项目WBS", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @Transactional
    public AjaxResult add(@RequestBody MaterialBill materialBill)
    {
        materialBill.setId(SnowFlakeUtils.nextId());
        materialBill.setMaterialid(materialBill.getProjectid());
        int i = materialBillService.insertMaterialBill(materialBill, "0");
        return toAjax(i);
    }

    /**
     * 修改项目WBS
     */
    @PreAuthorize("@ss.hasPermi('pms:ebom:edit')")
    @Log(title = "项目WBS", businessType = BusinessType.UPDATE)
    @PutMapping
    @Transactional
    public AjaxResult edit(@RequestBody MaterialBill materialBill)
    {
        int num=materialBillService.updateMaterialBill(materialBill);
        if(num==0){
            return AjaxResult.error();
        }else{
            return AjaxResult.success();
        }
    }

    /**
     * 删除项目WBS
     */
    @PreAuthorize("@ss.hasPermi('pms:ebom:remove')")
    @Log(title = "项目WBS", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @Transactional
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        int rows=0;
        Long materialid=0L;
        Long parentid=0L;
        for(Long id:ids){
            List<MaterialBill> materialBillList = materialBillService.selectMaterialBillSubordinate(id);
            if(materialBillList.size()>0){
                return AjaxResult.error("有下级BOM,请先删除下级BOM！");
            }
            MaterialBill materialbill = materialBillService.selectMaterialBillById(id);
            materialid=materialbill.getMaterialid();
            parentid=materialbill.getParentid();
            rows=materialBillService.deleteMaterialBillById(id);
            materialBillService.updateRank(parentid,materialid,"");
        }
        materialBillService.updateOrder(materialid);
        return toAjax(rows);
    }

    /**
     * 修改项目WBS，全编辑
     */
    @PreAuthorize("@ss.hasPermi('pms:ebom:edit')")
    @Log(title = "项目WBS", businessType = BusinessType.UPDATE)
    @PutMapping("/editAll")
    @Transactional
    public AjaxResult editAll(@RequestBody List<MaterialBill> materialBillList)
    {
        for(MaterialBill materialBill:materialBillList){
            int num=materialBillService.updateMaterialBill(materialBill);
            if(num==0){
                return AjaxResult.error();
            }
        }
        return AjaxResult.success();
    }


    /**
     * 修改项目WBS，批量编辑
     */
    @PreAuthorize("@ss.hasPermi('pms:ebom:edit')")
    @Log(title = "项目WBS", businessType = BusinessType.UPDATE)
    @PostMapping("/pmsbatch")
    @Transactional
    public AjaxResult pmsbatch(@RequestBody MaterialBill materialBill)
    {
        String idsStr=materialBill.getIds();
        String[] ids =idsStr.split(",");
        for(String id:ids){
            materialBill.setId(Long.valueOf(id));
            int num=materialBillService.updateMaterialBill(materialBill);
            if(num==0){
                return AjaxResult.error();
            }
        }
        return AjaxResult.success();
    }

    /**
     * 新增同级
     */
    @PreAuthorize("@ss.hasPermi('pms:ebom:add')")
    @Log(title = "项目WBS", businessType = BusinessType.INSERT)
    @PostMapping("/addPrepend")
    @Transactional
    public AjaxResult addPrepend(@RequestBody MaterialBill materialBill)
    {
        if(0==materialBill.getParentid()){
            return AjaxResult.error("新增同级BOM请勿选中层级为0的数据添加，添加同级BOM失败");
        }
        return toAjax(materialBillService.insertMaterialBill(materialBill,"1"));
    }

    /**
     * 新增上级
     */
    @PreAuthorize("@ss.hasPermi('pms:ebom:add')")
    @Log(title = "项目WBS", businessType = BusinessType.INSERT)
    @PostMapping("/addSuperior")
    @Transactional
    public AjaxResult addSuperior(@RequestBody MaterialBill materialBill)
    {
        Long userId = SecurityUtils.getUserId();
        materialBill.setOwnerid(userId.intValue());
        materialBill.setId(SnowFlakeUtils.nextId());
        //根据上层id判断是否顶层
        MaterialBill materialBillp = materialBillService.selectMaterialBillById(materialBill.getParentid());

        if(materialBillp.getParentid().equals(materialBill.getMaterialid())){
            return AjaxResult.error("当前位置已是最上级位置无法继续往上添加，添加上级BOM失败");
        }
        System.out.println("materialBill========="+materialBill);
        int row=materialBillService.insertMaterialBill(materialBill,"2");
        if(row==-1) {
            return AjaxResult.error("当前位置已是最上级位置无法继续往上添加，添加上级BOM失败");
        }
        return toAjax(row);
    }

    /**
     * 克隆EBOM
     */
    @PreAuthorize("@ss.hasPermi('pms:ebom:add')")
    @Log(title = "克隆EBOM", businessType = BusinessType.INSERT)
    @PostMapping("/cloneEBOM")
    @Transactional
    public AjaxResult cloneEBOM(@RequestBody Sharing rdaPmsassignRel)
    {
        String idsStr=rdaPmsassignRel.getIds();
        String[] ids =idsStr.split(",");
        Long toid= Long.valueOf(ids[0]);
        Long tmpdate=System.currentTimeMillis();
        Long tmptime = Long.valueOf(String.valueOf(tmpdate/1000));
        MaterialBill materialBill=new MaterialBill();
        if("0".equals(rdaPmsassignRel.getPmsid())){
            MaterialBill rp=materialBillMapper.selectMaterialBillById(Long.parseLong(rdaPmsassignRel.getPmsid()));
            materialBill.setLevel(rp.getLevel());
        }else{
            materialBill.setLevel(0);
        }
        materialBill.setParentid(toid);
        materialBill.setProjectid(rdaPmsassignRel.getProjectid());
        materialBill.setTmptime(tmptime);
        materialBill.setTmpid(toid);
        materialBill.setTmpParentid(Long.parseLong(rdaPmsassignRel.getPmsid()));

        int row = materialBillService.cloneEBOM(materialBill);
        if(row==-1){
            return AjaxResult.error("抱歉你选中的零件没有EBOM下级数据，克隆EBOM失败");
        }else{
            return toAjax(row);
        }
    }


    // TODO: 2023/11/16 修该原有
    /**
     * 查找零部件类型材料下的所有零件
     */
//    @PreAuthorize("@ss.hasPermi('pms:ebom:list')")
//    @GetMapping("/lists")
//    public TableDataInfo lists(@RequestParam(required = false) String searchValue)
//    {
//        RdaPart rdaParts = new RdaPart();
//        rdaParts.setTypeid(10002293L);
//        List<RdaPart> rdaPart3 =new ArrayList<>();
//        List<RdaPart>  materialTree=rdaMaterialService.selectRdaPartTreeList(rdaParts);
//        System.out.println("查询物料分类表====================="+materialTree.size()+"===="+materialTree);
//        //筛选出顶级
//        materialTree.forEach((RdaPart rdaPart2)->{
//            if(!rdaPart2.getParentid().equals(0L)){
//                rdaPart2.setProjectid(null);
//                rdaPart3.add(rdaPart2);
//            }
//        });
//        System.out.println("rdaPart3====================="+rdaPart3.size()+"===="+rdaPart3);
//        LinkedList<MaterialBill> materialBills = new LinkedList<>();
//        for (RdaPart rdaPart : rdaPart3) {
//            MaterialBill bill=new MaterialBill();
//            bill.setLevel(0);
//            bill.setRank(String.valueOf(0));
//            bill.setRdorder(0);
//            bill.setId(rdaPart.getId());
//            bill.setParentid(0L);
//            bill.setMaterialid(rdaPart.getId());
//            bill.setName(rdaPart.getName());
//            bill.setCode(rdaPart.getCode());
//            bill.setDescription(rdaPart.getDescription());
//            bill.setTypeid(Math.toIntExact(rdaPart.getTypeid()));
//            bill.setPolicyid(Math.toIntExact(rdaPart.getPolicyid()));
//            bill.setStateid(Math.toIntExact(rdaPart.getStateid()));
//            MaterialBill materialBill = new MaterialBill();
//            materialBill.setMaterialid(rdaPart.getId());
//            materialBill.setSearchValue(searchValue);
//            List<MaterialBill> list = materialBillService.selectMaterialBillList(materialBill);
//            System.out.println("list========="+list.size()+"======="+list);
//            if(!CollectionUtils.isEmpty(list)){
//                materialBills.add(bill);
//                if (searchValue!=null){
//                    for (MaterialBill materialBill1 : list) {
//                        List<MaterialBill> hierarchyU = materialBillService.getHierarchyU(materialBill1.getId());
//                        for (MaterialBill materialBill2 : hierarchyU) {
//                            if (!materialBills.contains(materialBill2)){
//                                materialBills.add(materialBill2);
//                            }
//                        }
//                    }
//                }else {
//                    materialBills.addAll(list);
//                }
//            }
//        }
//        return getDataTable(materialBills);
//    }

    @PreAuthorize("@ss.hasPermi('pms:ebom:list')")
    @GetMapping("/lists")
    public TableDataInfo lists(MaterialBill materialBill){
        List<MaterialBill> materialBillList = materialBillService.selectMaterialBillByAll(materialBill);
        return getDataTable(materialBillList);
    }

    /**
     * 插入现有零件作为子级
     */
    @PreAuthorize("@ss.hasPermi('pms:ebom:add')")
    @Log(title = "插入现有零件作为子级", businessType = BusinessType.INSERT)
    @PostMapping("/InsertExistAsChild")
    public AjaxResult InsertExistAsChild(@RequestBody Sharing rdaPmsassignRel)
    {
        materialBillService.InsertExistAsChild(rdaPmsassignRel);
        return AjaxResult.success();
    }


    /**
     * 插入下一现有零件,前端需要传递被插入物料的tmpid、tmpParentid、tmpLevel
     */

//    @PreAuthorize("@ss.hasPermi('pms:ebom:add')")
//    @Log(title = "插入下一现有零件", businessType = BusinessType.INSERT)
//    @PostMapping("/addExist")
//    public AjaxResult addExist(@RequestBody Sharing rdaPmsassignRel)
//    {
//        //插入id
//        String idsStr=rdaPmsassignRel.getIds();
//        String[] ids =idsStr.split(",");
//        Long tid= Long.valueOf(ids[0]);
//        //如果物料表没有信息标识中的是根节点
//        MaterialBill mb = materialBillMapper.selectMaterialBillById(tid);
//        if (mb==null){
//            return AjaxResult.error("不能选择根节点");
//        }
//        materialBillService.hierarchyUpdate(rdaPmsassignRel);
//        return AjaxResult.success();
//    }

    /**
     * 插入下一现有零件作为同级Ebom
     * @param rdaPmsassignRel
     * @return
     */
    @PreAuthorize("@ss.hasPermi('pms:ebom:add')")
    @Log(title = "插入下一现有零件作为同级", businessType = BusinessType.INSERT)
    @PostMapping("/addExist")
    public AjaxResult addExist(@RequestBody Sharing rdaPmsassignRel)
    {
        materialBillService.hierarchyUpdates(rdaPmsassignRel);
        return AjaxResult.success();
    }

    /**
     * 插入下一现有零件作为上级Ebom
     * @param rdaPmsassignRel
     * @return
     */
    @PreAuthorize("@ss.hasPermi('pms:ebom:add')")
    @Log(title = "插入下一现有零件作为上级", businessType = BusinessType.INSERT)
    @PostMapping("/insertParent")
    public AjaxResult insertParent(@RequestBody Sharing rdaPmsassignRel)
    {
        materialBillService.insertParent(rdaPmsassignRel);
        return AjaxResult.success();
    }

    /**
     * 移除物料（移除的是关系）
     */
//需要前端传输param，key为type来标记是否使用bom拷贝
    @PreAuthorize("@ss.hasPermi('pms:ebom:remove')")
    @Log(title = "移除EBOM", businessType = BusinessType.DELETE)
    @DeleteMapping("removeEbom/{ids}")
    @Transactional
    public AjaxResult removeEbom(@PathVariable Long[] ids){
        iMaterialBillService.removeEbom(ids);
        return AjaxResult.success();
    }


    /**
     * 标识号重新排序
     */
    @PreAuthorize("@ss.hasPermi('pms:ebom:list')")
    @Log(title = "标识号重新排序", businessType = BusinessType.OTHER)
    @GetMapping("/rankSort/{ids}")
    @Transactional
    public AjaxResult rankSort(@PathVariable Long[] ids){
        iMaterialBillService.rankSort(ids);
//        for (Long id : ids) {
//            MaterialBill materialBill = materialBillService.selectMaterialBill(id);
//            materialBillService.updateLevel(materialBill.getId(),materialBill.getLevel());
//            materialBillService.updateRank(id,materialBill.getMaterialid(),"");
//            materialBillService.updateOrder(materialBill.getMaterialid());
//        }
        return AjaxResult.success();
    }

    @PreAuthorize("@ss.hasPermi('pms:ebom:remove')")
    @Log(title = "替换对像", businessType = BusinessType.INSERT)
    @PostMapping("/viewSort")
    @Transactional
    public AjaxResult viewSort(@RequestBody Sharing rdaRestrainwbsRel){
        String tRank;
        String fRank;
        String idsStr=rdaRestrainwbsRel.getIds();
        String[] ids =idsStr.split(",");
        Long tid= Long.valueOf(ids[0]);
        MaterialBill materialBillT = materialBillService.selectMaterialBillById(Long.parseLong(rdaRestrainwbsRel.getToid()));
        MaterialBill materialBillF= materialBillService.selectMaterialBillById(tid);
        tRank=materialBillT.getRank();
        fRank=materialBillF.getRank();
        materialBillT.setRank(fRank);
        materialBillF.setRank(tRank);
        materialBillService.updateMaterialBill(materialBillT);
        materialBillService.updateMaterialBill(materialBillF);
        return AjaxResult.success();
    }


    /**
     * 复制到
     */
    @PreAuthorize("@ss.hasPermi('pms:ebom:remove')")
    @Log(title = "复制到", businessType = BusinessType.INSERT)
    @PostMapping("/copyTo")
    @Transactional
    public AjaxResult copyTo(@RequestBody Sharing rdaRestrainwbsRel){
        //表单id
        //插入id
        String idsStr=rdaRestrainwbsRel.getIds();
        String[] ids =idsStr.split(",");
        Long tid= Long.valueOf(ids[0]);
        //如果物料表没有信息标识中的是根节点
//        MaterialBill materialBillF = materialBillMapper.selectMaterialBillById(tid);
//        if (materialBillF==null){
//            return AjaxResult.error("不能选择根节点");
//        }
        //表格id
        MaterialBill materialBillT = materialBillMapper.selectMaterialBillById(Long.parseLong(rdaRestrainwbsRel.getToid()));
        if (materialBillT==null){
            return AjaxResult.error("不能选择根节点");
        }

        materialBillService.copyTo(rdaRestrainwbsRel);
//        materialBillT.setLevel(materialBillF.getLevel()+1);
//        materialBillT.setParentid(materialBillF.getId());
//        materialBillService.updateMaterialBill(materialBillT);
        return AjaxResult.success();
    }

    /**
     * 复制自
     */
    @PreAuthorize("@ss.hasPermi('pms:ebom:list')")
    @GetMapping("/copyFromList")
    public TableDataInfo copyFromList(MaterialBill materialBill)
    {
        startPage();
        RdaPart rdaPart=rdaMaterialService.selectRdaPartByid(materialBill.getMaterialid());
        MaterialBill bill=new MaterialBill();
        bill.setLevel(0);
        bill.setRank(String.valueOf(0));
        bill.setRdorder(0);
        bill.setId(rdaPart.getId());
        bill.setParentid(0L);
        bill.setMaterialid(rdaPart.getId());
        bill.setName(rdaPart.getName());
        bill.setCode(rdaPart.getCode());
        bill.setDescription(rdaPart.getDescription());
        bill.setTypeid(Math.toIntExact(rdaPart.getTypeid()));
        bill.setPolicyid(Math.toIntExact(rdaPart.getPolicyid()));
        bill.setStateid(Math.toIntExact(rdaPart.getStateid()));
        List<MaterialBill> list = materialBillService.selectMaterialBillList(materialBill);
        List<MaterialBill> treeList = new ArrayList<>();
        if (materialBill.getSearchValue()!=null){
            for (MaterialBill materialBill1 : list) {
                List<MaterialBill> hierarchyU = materialBillService.getHierarchy(materialBill1.getId());
                MaterialBill materialBill3 = materialBillService.selectMaterialBillById(materialBill1.getId());
                if (!treeList.contains(materialBill3)){
                    treeList.add(materialBill3);
                }
                for (MaterialBill materialBill2 : hierarchyU) {
                    if (!treeList.contains(materialBill2)){
                        treeList.add(materialBill2);
                    }
                }
            }
        }else {
            treeList=list;
        }

//        //如何能让树形展示，需要重新调整revel
//        Integer minLevel = treeList.stream()
//                .map(MaterialBill::getLevel)
//                .min(Integer::compareTo)
//                .orElse(null);
//
//        Integer temp = minLevel-1;
//        List<MaterialBill> updatedList = treeList.stream()
//                .map(mb -> {
//                    int newLevel = mb.getLevel() - temp;
//                    mb.setLevel(newLevel);
//                    return mb;
//                })
//                .collect(Collectors.toList());
//        updatedList.add(0,bill);

        treeList.add(0,bill);

        return getDataTable(treeList);
    }


    @PreAuthorize("@ss.hasPermi('pms:ebom:remove')")
    @Log(title = "复制自", businessType = BusinessType.INSERT)
    @PostMapping("/copyFrom")
    @Transactional
    public AjaxResult copyFrom(@RequestBody Sharing rdaPmsassignRel){
        //表单id
        //插入id
        String idsStr=rdaPmsassignRel.getIds();
        String[] ids =idsStr.split(",");
        //如何表单选中的包含根节点,则进行提示
        for (String id : ids) {
            Long tid= Long.valueOf(id);
            MaterialBill materialBillF = materialBillMapper.selectMaterialBillById(tid);
            if (materialBillF==null){
                return AjaxResult.error("不能选择根节点");
            }
        }
        //表格id
        MaterialBill materialBillT = materialBillMapper.selectMaterialBillById(Long.parseLong(rdaPmsassignRel.getPmsid()));
        if (materialBillT==null){
            return AjaxResult.error("不能选择根节点");
        }

        for (String id : ids) {
            Long tid= Long.valueOf(id);
            MaterialBill materialBillF = materialBillMapper.selectMaterialBillById(tid);
            materialBillF.setLevel(materialBillT.getLevel()+1);
            materialBillF.setParentid(materialBillT.getId());
            materialBillService.updateMaterialBill(materialBillF);
        }


        return AjaxResult.success();
    }

    /**
     * 引用项目反查
     */

    @PreAuthorize("@ss.hasPermi('pms:ebom:list')")
    @GetMapping("/reverseList")
    public AjaxResult reverseList(MaterialBill md){
        MaterialBill materialBill = materialBillService.selectMaterialBillById(md.getId());
        if (materialBill==null){
            return AjaxResult.error("不能选根节点");
        }
        List<MaterialBill> hierarchyU = materialBillService.getHierarchyU(md.getId());
//        hierarchyU.remove(materialBill);
////        //查询过滤
////        if (md.getSearchValue()!=null){
////            List<MaterialBill> collect = hierarchyU.stream()
////                    .filter(bill -> bill.getName().contains(md.getSearchValue()))
////                    .collect(Collectors.toList());
////            return AjaxResult.success(collect);
////        }
        List<MaterialBill> filteredList = hierarchyU.stream()
                .limit(1)
                .collect(Collectors.toList());
        return AjaxResult.success(filteredList);
    }

    /**
     * 多级报告
     */
    @PreAuthorize("@ss.hasPermi('pms:ebom:list')")
    @GetMapping("/reportList")
    public TableDataInfo reportList(MaterialBill materialBill,String relation,String levels)
    {
        startPage();
        List<MaterialBill> list = materialBillService.selectMaterialBillList(materialBill);
        if (levels!=null){
            if ("1".equals(relation)){
                List<MaterialBill> collect = list.stream().filter(mb -> mb.getLevel() <= Integer.parseInt(levels)).collect(Collectors.toList());
                return getDataTable(collect);
            }else {
                materialBill.setLevel(Integer.parseInt(levels));
                list = materialBillService.selectMaterialBillList(materialBill);
            }
        }
        return getDataTable(list);
    }


    /**
     * 综合报告
     */
    @PreAuthorize("@ss.hasPermi('pms:ebom:list')")
    @GetMapping("/ComprehensiveList")
    public TableDataInfo ComprehensiveList(MaterialBill materialBill,String relation,String levels)
    {
        startPage();
        List<MaterialBill> list = materialBillService.selectMaterialBillList(materialBill);
        List<MaterialBill> mergedList = list.stream()
            .collect(
                    Collectors.collectingAndThen(
                            Collectors.toMap(
                                    MaterialBill::getName,
                                    mb -> mb,
                                    (mb1, mb2) -> {
                                        mb1.setNumber(mb1.getNumber() + mb2.getNumber());
                                        return mb1;
                                    }
                            ),
                            map -> new ArrayList<>(map.values())
                    )
            );

        if (levels!=null){
            if ("1".equals(relation)){
                List<MaterialBill> collect = list.stream().filter(mb -> mb.getLevel() <= Integer.parseInt(levels)).collect(Collectors.toList());
                return getDataTable(collect);
            }else {
                materialBill.setLevel(Integer.parseInt(levels));
                list = materialBillService.selectMaterialBillList(materialBill);
                mergedList = list.stream()
                        .collect(
                                Collectors.collectingAndThen(
                                        Collectors.toMap(
                                                MaterialBill::getName,
                                                mb -> mb,
                                                (mb1, mb2) -> {
                                                    mb1.setNumber(mb1.getNumber() + mb2.getNumber());
                                                    return mb1;
                                                }
                                        ),
                                        map -> new ArrayList<>(map.values())
                                )
                        );
            }
        }
        return getDataTable(mergedList);
    }


    /**
     * 对比报告
     */
    @PreAuthorize("@ss.hasPermi('pms:ebom:list')")
    @GetMapping("/compareReport")
    public AjaxResult compareReport(@RequestParam(value = "id") Long id,@RequestParam(value = "type",defaultValue = "0") String type){
        return AjaxResult.success(materialBillService.compareReport(id,type));
    }

    /**
     * 对比报告同版本号的数据
     */
    @PreAuthorize("@ss.hasPermi('pms:ebom:list')")
    @GetMapping("/compareRevi")
    public AjaxResult compareReport(@RequestParam(value = "name") String name,@RequestParam(value = "materialid") Long materialid){
        MaterialBill materialBill = new MaterialBill();
        materialBill.setName(name);
//        materialBill.setMaterialid(materialid);
        return AjaxResult.success(materialBillService.selectMaterialBillList(materialBill));
    }


    /**
     * 名称引用
     */
    @PreAuthorize("@ss.hasPermi('pms:material:query')")
    @GetMapping(value = "/sub/{id}")
    public JSONObject quote(@PathVariable("id") Long id)
    {
        System.out.println("进来了");
        JSONObject jsonobj = new JSONObject();
        StringBuilder json=new StringBuilder();
        RdaPart rdaPart = new RdaPart();
        MaterialBill materialBillT = materialBillService.selectMaterialBillById(id);
        if (materialBillT==null){
            rdaPart=rdaMaterialService.selectRdaPartByid(id);
        }
        else{
            MaterialBill materialBill = materialBillService.selectMaterialBillById(id);
            BeanUtils.copyProperties(materialBill,rdaPart);
            //获得系列id
            RdaPart rdaPartW = rdaMaterialService.selectRdaPartByid(materialBill.getMaterialid());
            //获取projectid
            System.out.println("materialBill======="+materialBill);
            rdaPart.setTypeid(Long.parseLong(materialBill.getTypeid().toString()));
            rdaPart.setPolicyid(Long.parseLong(materialBill.getPolicyid().toString()));
            rdaPart.setStateid(Long.parseLong(materialBill.getStateid().toString()));
            rdaPart.setProjectid(rdaPartW.getProjectid());
            System.out.println("rdaPart1======="+rdaPart);
        }
        String stringJSON = JSON.toJSONString(rdaPart);
        json.append(stringJSON);
        RdaPartDynamicattributevalue rdaPartDynamicattributevalue=new RdaPartDynamicattributevalue();
        rdaPartDynamicattributevalue.setObjectid(rdaPart.getId());
        List<RdaPartDynamicattributevalue> rdaPartDynamicattributevalueList=rdaPartDynamicattributevalueService.selectRdaPartDynamicattributevalueList(rdaPartDynamicattributevalue);
        String attribute = "";
        for(RdaPartDynamicattributevalue partDynamicattributevalue:rdaPartDynamicattributevalueList){
            attribute += ",\""+partDynamicattributevalue.getAttributeName()+"\":\""+partDynamicattributevalue.getAttributeValue()+"\"";//字符串两边含有双引号
        }
        if(attribute!=null && attribute.length()>0){
            json.insert(json.length()-1,attribute);
        }
        JSONObject jsonObject =  JSON.parseObject(json.toString());
        jsonobj.put("data",jsonObject);
        jsonobj.put("code",200);
        jsonobj.put("msg","操作成功");
        return jsonobj;

    }

    @PreAuthorize("@ss.hasPermi('pms:material:query')")
    @GetMapping(value = "/ReferenceChain/{id}")
    public String ReferenceChain(@PathVariable("id") Long id){
        return materialBillService.ReferenceChain(id);
    }


    /**
     * 引用者
     *
     */
    @GetMapping(value = "/referrer")
    public TableDataInfo referrer(MaterialBill materialBill){
        List<MaterialBill> referrer = materialBillService.referrer(materialBill);
        return getDataTable(referrer);
    }


    /**
     * 复制与剪切
     */
    @PostMapping(value = "/copy")
    public AjaxResult copywbs(@RequestBody List<Sharing> sharing){
        iMaterialBillService.copywbs(sharing);
        return AjaxResult.success();
    }



}
